import requests
import json
import time


class Book:
    def __init__(self, name, code, author, price):
        self.name = name
        self.code = code
        self.author = author
        self.price = price

    def __str__(self):
        return f'书名：{self.name}，作者：{self.author}，价格：{self.price}，编号：{self.code}'


def get_page(page=1):
    '''抓取指定页的数据，默认是第1页'''
    # 使用page动态拼接URL
    url = f'https://www.epubit.com/pubcloud/content/front/portal/getUbookList?page={page}&row=20&=&startPrice=&endPrice=&tagId='
    headers = {'Origin-Domain': 'www.epubit.com'}
    # 请求的时候同时传入headers
    res = requests.get(url, headers=headers)
    books = parse_book(res.text)
    return books


def parse_book(json_text):
    '''根据返回的JSON字符串，解析书的列表'''
    books = []
    # 把JSON字符串转成一个字典dict类
    book_json = json.loads(json_text)
    records = book_json['data']['records']
    for r in records:
        author = r['authors']
        name = r['name']
        code = r['code']
        price = r['price']
        book = Book(name, code, author, price)
        books.append(book)
    return books


all_books = []
for i in range(1, 10):
    print(f'======抓取第{i}页======')
    books = get_page(i)
    for b in books:
        print(b)
    all_books.extend(books)
    print('抓完一页，休息5秒钟...')
    time.sleep(5)
